package com.jblv.frame.web.facade.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.plugins.Page;
import com.jblv.frame.common.constants.BaseConstant;
import com.jblv.frame.common.dto.PageResult;
import com.jblv.frame.common.dto.UserTokenDTO;
import com.jblv.frame.common.enums.ExceptionEnum;
import com.jblv.frame.common.exception.FrameException;
import com.jblv.frame.common.utils.*;
import com.jblv.frame.web.facade.ISysUserFacade;
import com.jblv.frame.user.api.bll.ISysUserBLL;
import com.jblv.frame.user.api.dto.SysUserDTO;
import com.jblv.frame.user.api.dto.UserLoginResultDTO;
import com.jblv.frame.user.api.entity.SysUser;
import com.jblv.frame.user.api.params.UserLoginParams;
import com.jblv.frame.user.api.params.SysUserListParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title SysUserFacade
 * @projectName jblv-frame
 * @packageName com.jblv.web.facade.impl
 * @description 用户信息门面实现类
 * @date Create at 2020/4/28 21:17
 * @since jdk1.8
 */
@Service
public class SysUserFacade implements ISysUserFacade {

    private static final Logger logger = LoggerFactory.getLogger(SysUserFacade.class);

    //    @Autowired
    @Reference(check = false)
    ISysUserBLL sysUserBLL;


    @Override
    public UserLoginResultDTO get() {
        String operUserId = (String)RequestHolder.get(RequestHolder.OPER_USER_ID);

        UserLoginResultDTO userLoginResultDTO = new UserLoginResultDTO();
        SysUser sysUser = null;
        try {
            sysUser = sysUserBLL.get(operUserId);
        }catch (Exception e){
            logger.error("获取用户信息错误");
            e.printStackTrace();
        }
        BeanUtils.copyProperties(sysUser,userLoginResultDTO);
        List<String> roles = new ArrayList<>();
        roles.add("admin");
        userLoginResultDTO.setRoles(roles);
        return userLoginResultDTO;
    }

    @Override
    public SysUser get(String id){
        return sysUserBLL.get(id);
    }

    @Override
    public PageResult<SysUserDTO> getList(SysUserListParams params) {
        List<SysUserDTO> listDTO = new ArrayList<>();

        PageResult<SysUserDTO> result = new PageResult<>();
        result.setPageSize(params.getLimit());
        result.setCurPage(params.getPage());
        result.setList(listDTO);

        Page<SysUser> page = sysUserBLL.getList(params);

        List<SysUser> list = page.getRecords();
        result.setTotal(page.getTotal());

        if (!CollectionUtils.isEmpty(list)) {
            SysUserDTO dto = null;
            for (SysUser bean : list) {
                dto = new SysUserDTO();

                dto.setUserId(bean.getUserId());
                dto.setUserName(bean.getUserName());
                dto.setCreateTime(bean.getCreateTime());
                dto.setCreator(bean.getCreator());
                dto.setUpdateTime(bean.getUpdateTime());
                dto.setUpdater(bean.getUpdater());
                dto.setLoginName(bean.getLoginName());
                dto.setLoginIp(bean.getLoginIp());
                dto.setStatus(bean.getStatus());
                dto.setMobile(bean.getMobile());
                dto.setEmail(bean.getEmail());
                dto.setSex(bean.getSex());
                dto.setRemark(bean.getRemark());

                listDTO.add(dto);
            }
        }
        return result;
    }

    @Override
    public Boolean del(String id) {
        String operUserId = (String)RequestHolder.get(RequestHolder.OPER_USER_ID);

        Boolean isDel = false;
        try {
            isDel = sysUserBLL.remove(operUserId, id);
        }catch (Exception e){
            logger.error("管理员删除失败");
            e.printStackTrace();
        }
        if (!isDel){
            throw new FrameException(ExceptionEnum.DATA_DELETE_FAILE);

        }

        return isDel;
    }

    @Override
    public String create(SysUserDTO sysUserDTO) {
        String operUser = (String)RequestHolder.get(RequestHolder.OPER_USER_NAME);

        SysUser sysUser = new SysUser();

        BeanUtils.copyProperties(sysUserDTO, sysUser);
        String id = null;
        try {
            id = sysUserBLL.save(operUser, sysUser);
        }catch (Exception e){
            logger.error("管理员保存失败");
            e.printStackTrace();
        }
        if(StringUtils.isEmpty(id)){
            throw new FrameException(ExceptionEnum.DATA_CREATE_FAILE);
        }

        return id;
    }

    @Override
    public Boolean update(SysUserDTO sysUserDTO) {
        String operUser = (String)RequestHolder.get(RequestHolder.OPER_USER_NAME);

        SysUser sysUser = new SysUser();

        BeanUtils.copyProperties(sysUserDTO, sysUser);

        Boolean isUpdate = false;

        try {
            isUpdate = sysUserBLL.update(operUser, sysUser);
        }catch (Exception e){
            logger.error("管理员更新失败");
            e.printStackTrace();
        }

        if(!isUpdate){
            throw new FrameException(ExceptionEnum.DATA_UPDATE_FAILE);
        }

        return isUpdate;
    }

    @Override
    public Boolean status(String userId, Integer status) {
        String operator = (String)RequestHolder.get(RequestHolder.OPER_USER_NAME);
        Boolean isUpdate = false;

        try {
            isUpdate = sysUserBLL.updateStatusById(userId, status, operator);
        }catch (Exception e){
            logger.error("管理员状态更新失败");
            e.printStackTrace();
        }

        if(!isUpdate){
            throw new FrameException(ExceptionEnum.DATA_UPDATE_FAILE);
        }

        return isUpdate;
    }

    @Override
    public UserTokenDTO pwdLogin(UserLoginParams params) {
        if (params == null) {
            throw new FrameException(ExceptionEnum.PARAM_ERROR);
        }
        UserTokenDTO userTokenDTO = new UserTokenDTO();
        String userType = params.getUserType();
        String userName = params.getUsername();
        String pwd = params.getPassword();

        if(StringUtils.isEmpty(userName)){
            throw new FrameException(ExceptionEnum.USER_USERNAME_EMPTY);
        }

        if(StringUtils.isEmpty(pwd)){
            throw new FrameException(ExceptionEnum.USER_PASSWORD_EMPTY);
        }

        SysUser userInfo = sysUserBLL.getUserByUserName(userName);
        String roleType = "";
        String deptName = "";

        if (userInfo == null || !PasswordUtils.sha256(userInfo.getSalt(),pwd).equals(userInfo.getPassword())) {
            throw new FrameException(ExceptionEnum.USER_PASSWORD_ERROR);
        }

        // 生成token
        String token = UserTokenUitls.createAccessToken("",userInfo.getUserId(),userInfo.getMobile(),userName,roleType,userInfo.getUserType(), userInfo.getAvatar(),userInfo.getDeptId(), deptName);
        userTokenDTO.setProjectName(BaseConstant.PLATFORM_NAME);
        userTokenDTO.setToken(token);
        userTokenDTO.setUserType(userType);
        userTokenDTO.setUserId(userInfo.getUserId());
        userTokenDTO.setMobile(userInfo.getMobile());
        userTokenDTO.setUserName(userInfo.getLoginName());


        return userTokenDTO;
    }

    @Override
    public Boolean logout() {
        RequestHolder.remove();
        return true;
    }
}
